"""
# @Description: user视图类
# @Author: chen990627
# @Date: 2022/03/08
"""
import json
import logging
import jwt
from jwt import api_jwt
from user.models import UserInfo
from django.http import HttpResponse, JsonResponse
from django.contrib.auth import authenticate, login
from rest_framework.decorators import api_view, authentication_classes, permission_classes
from rest_framework.permissions import IsAuthenticated, AllowAny
from user.serializers import UserInfoSerializer
from rest_framework import mixins, generics, viewsets, permissions
from rest_framework_jwt.authentication import JSONWebTokenAuthentication
from rest_framework_jwt.settings import api_settings
from rest_framework.parsers import JSONParser
# Create your views here.

jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
jwt_decode_handler = api_settings.JWT_DECODE_HANDLER

@api_view(http_method_names=['POST'])
@permission_classes([AllowAny,])
def user_login(request):
    request_data = json.loads(request.body)
    username = request_data.get("username")
    password = request_data.get("password")

    if username is None or password is None:
        return JsonResponse({'code': 500, 'message': '请求参数错误'})
    is_login = authenticate(request, username=username, password=password)
    if is_login is None:
        return JsonResponse({'code': 500, 'message': '账号或密码错误'})

    login(request, is_login)
    payload = jwt_payload_handler(is_login)
    token = jwt_encode_handler(payload)

    return JsonResponse({'code': 200, 'message': '登录成功', 'data': {'token': token}})

@api_view(['POST'])
@permission_classes([AllowAny,])
def user_register(request):
    request_data = json.loads(request.body)
    username = request_data.get('username')
    password = request_data.get('password')
    email = request_data.get('email')
    user_phone = request_data.get('user_phone')

    if UserInfo.objects.filter(username=username):
        logging.error("该用户已存在！")
    else:
        UserInfo.objects.create_user(username=username, password=password, email=email, user_phone=user_phone)
    return JsonResponse({'code': 200, 'message': '注册成功'})

@api_view(['GET'])
@authentication_classes((JSONWebTokenAuthentication,))
def user_info(request):
    try:
        token = request.data.get("Authorization").split(" ")[1]
        token_user = jwt_decode_handler(token)
        user_id = token_user["user_id"]
    except jwt.exceptions.ExpiredSignatureError:
        return JsonResponse({"message": "token已失效"}, status=401)
    serializer = UserInfoSerializer(UserInfo.objects.filter(id=user_id), many=True)
    return JsonResponse(serializer.data, safe=False)

